package com.itany.websocket.websocket.websocket;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//Web Socket请求处理类
public class SpringWebSocketHandler extends TextWebSocketHandler {

    public static Map<String,WebSocketSession> users=new ConcurrentHashMap<>();

    //连接成功时触发
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("连接成功----------------------");
        String nickname= (String) session.getAttributes().get("nickname");
        users.put(nickname,session);
    }

    //连接关闭时触发
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接关闭----------------------");
        String nickname= (String) session.getAttributes().get("nickname");
        users.remove(nickname);
    }

    //连接异常时触发
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("连接异常----------------------");
        String nickname= (String) session.getAttributes().get("nickname");
        users.remove(nickname);
    }

    //客户端消息推送时触发
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("客户端请求----------------------");
        System.out.println("message = " + message);
        String nickname= (String) session.getAttributes().get("nickname");
        System.out.println("nickname = " + nickname);
        for (String name : users.keySet()) {
            synchronized (nickname){
                if(session.isOpen()) {
                    //服务器向客户端推送消息
                    users.get(name).sendMessage(new TextMessage(nickname + ":" + message.getPayload() + " " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
                }
            }
        }
    }
}
